package pers.rcl.utils;

import com.jfinal.kit.Prop;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Config;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.jbolt.common.config.MainConfig;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * What：高频常用方法集合<br>
 * Where：xx.xxx简短快捷的输入操作<br>
 * Why：整合高频常用方法,编码速度+50%,代码量-70%
 *
 * @author rcl
 */
public class xx {

	/**
	 * SYS数据源名称 默认数据源
	 **/
	public static final String DS_SYS = "sys";

	private static ThreadLocal<HttpServletRequest> _request = new ThreadLocal<HttpServletRequest>();

	public static void setRequest(HttpServletRequest request) {
		_request.set(request);
	}

	public static HttpServletRequest getRequest() {
		return _request.get();
	}

	public static String getPara(String name, String defaultValue) {
		String result = _request.get().getParameter(name);
		return result != null && !"".equals(result) ? result : defaultValue;
	}

	public static void removeRequest() {
		_request.remove();
	}

	/**
	 * @Description: 获取当前登录用户
	 * @param: @return
	 * @return: User
	 */
	public static Record getUser() {
		Record user = (Record) _request.get().getSession().getAttribute("user");
		if (user == null) {
			user = new Record();
		}
		return user;
	}

	/**
	 * <pre>
	 * 判空 Collection、Map、数组、Iterator、Iterable 类型对象中的元素个数是否为 0 规则：
	 * 1：null 返回 true
	 * 2：List、Set 等一切继承自 Collection 的，返回 isEmpty()
	 * 3：Map 返回 isEmpty()
	 * 4：数组返回 length == 0
	 * 5：Iterator 返回 ! hasNext()
	 * 6：Iterable 返回 !
	 * iterator().hasNext()
	 * </pre>
	 */
	public static boolean isEmpty(Object o) {
		if (o == null) {
			return true;
		}
		if (o instanceof String) {
			if (o.toString().equals("")) {
				return true;
			}
		}
		if (o instanceof Collection) {
			return ((Collection<?>) o).isEmpty();
		}
		if (o instanceof Map) {
			return ((Map<?, ?>) o).isEmpty();
		}
		if (o.getClass().isArray()) {
			return Array.getLength(o) == 0;
		}
		if (o instanceof Iterator) {
			return !((Iterator<?>) o).hasNext();
		}
		if (o instanceof Iterable) {
			return !((Iterable<?>) o).iterator().hasNext();
		}
		return false;
	}

	/**
	 * 是否为数字
	 *
	 * @param obj
	 * @return
	 */
	public static boolean isNum(Object obj) {
		try {
			Integer.parseInt(obj.toString());
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 字符串是否为 true
	 *
	 * @param str
	 * @return
	 */
	public static boolean isTrue(Object str) {
		if (isEmpty(str)) {
			return false;
		}
		str = str.toString().trim().toLowerCase();
		if (str.equals("true") || str.equals("on")) {
			return true;
		}
		return false;
	}

	/**
	 * 格式化字符串->'str'
	 *
	 * @param str
	 * @return
	 */
	public static String format(Object str) {
		return "'" + str.toString() + "'";
	}

	/**
	 * 强转->Integer
	 *
	 * @param obj
	 * @return
	 */
	public static Integer toInt(Object obj) {
		return Integer.parseInt(obj.toString());
	}

	/**
	 * 强转->Integer
	 *
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static Integer toInt(Object obj, int defaultValue) {
		if (isEmpty(obj)) {
			return defaultValue;
		}
		return toInt(obj);
	}

	/**
	 * 强转->Long
	 *
	 * @param obj
	 * @return
	 */
	public static long toLong(Object obj) {
		return toLong(obj, 0);
	}

	/**
	 * 强转->Long
	 *
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static long toLong(Object obj, long defaultValue) {
		if (obj == null) {
			return defaultValue;
		} else if (obj instanceof Long) {
			return (long) obj;
		} else {
			try {
				return Long.parseLong(obj.toString());
			} catch (Exception e) {
				return defaultValue;
			}
		}
	}

	/**
	 * 强转->Double
	 *
	 * @param obj
	 * @return
	 */
	public static double toDouble(Object obj, long defaultValue) {
		if (obj == null) {
			return defaultValue;
		} else if (obj instanceof Double) {
			return (double) obj;
		} else {
			try {
				return Double.parseDouble(obj.toString());
			} catch (Exception e) {
				return defaultValue;
			}
		}
	}

	public static double toDouble(Object obj) {
		return toDouble(obj, 0);
	}

	public static <T> T listGet(List<T> list, int index) {
		if (list == null || index >= list.size()) {
			return null;
		} else {
			return list.get(index);
		}
	}

	/**
	 * 强转->Boolean
	 *
	 * @param obj
	 * @return
	 */
	public static Boolean toBoolean(Object obj) {
		return Boolean.parseBoolean(obj.toString());
	}

	/**
	 * 强转->Boolean
	 *
	 * @param obj
	 * @param defaultValue
	 * @return
	 */
	public static Boolean toBoolean(Object obj, Boolean defaultValue) {
		if (isEmpty(obj)) {
			return defaultValue;
		}
		return toBoolean(obj);
	}

	/**
	 * Array转字符串(用指定符号分割)
	 *
	 * @param array
	 * @param sign
	 * @return
	 */
	public static String join(Object[] array, char sign) {
		if (array == null) {
			return null;
		}
		int arraySize = array.length;
		int bufSize = (arraySize == 0 ? 0 : ((array[0] == null ? 16 : array[0].toString().length()) + 1) * arraySize);
		StringBuilder sb = new StringBuilder(bufSize);

		for (int i = 0; i < arraySize; i++) {
			if (i > 0) {
				sb.append(sign);
			}
			if (array[i] != null) {
				sb.append(array[i]);
			}
		}
		return sb.toString();
	}

	/**
	 * 删除开头字符串
	 *
	 * @param s
	 *            待处理字符串
	 * @param sign
	 *            需要删除的符号
	 * @return
	 */
	public static String delStart(String s, String sign) {
		if (s.startsWith(sign)) {
			return s.substring(s.lastIndexOf(sign) + sign.length(), s.length());
		}
		return s;
	}

	/**
	 * 删除末尾字符串
	 *
	 * @param s
	 *            待处理字符串
	 * @param sign
	 *            需要删除的符号
	 * @return
	 */
	public static String delEnd(String s, String sign) {
		if (xx.isEmpty(s)) {
			return s;
		}
		if (s.endsWith(sign)) {
			return s.substring(0, s.lastIndexOf(sign));
		}
		return s;
	}

	/**
	 * 格式化输出JSON
	 *
	 * @param json
	 * @return
	 */
	public static String formatJson(String json) {
		int level = 0;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < json.length(); i++) {
			char c = json.charAt(i);
			if (level > 0 && '\n' == sb.charAt(sb.length() - 1)) {
				sb.append(getLevelStr(level));
			}
			switch (c) {
			case '{':
			case '[':
				sb.append(c + "\n");
				level++;
				break;
			case ',':
				sb.append(c + "\n");
				break;
			case '}':
			case ']':
				sb.append("\n");
				level--;
				sb.append(getLevelStr(level));
				sb.append(c);
				break;
			default:
				sb.append(c);
				break;
			}
		}
		return sb.toString();
	}

	private static String getLevelStr(int level) {
		StringBuffer levelStr = new StringBuffer();
		for (int levelI = 0; levelI < level; levelI++) {
			levelStr.append("  ");
		}
		return levelStr.toString();
	}

	/**
	 * 替换空格,换行符等
	 *
	 * @param s
	 * @return
	 */
	public static String replaceBlank(String s) {
		if (xx.isEmpty(s)) {
			return s;
		}
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(s);
		return m.replaceAll("");
	}

	public static String avoidNull(String s) {
		return s == null ? "" : s;
	}

	/**
	 * 比较long是否相等
	 *
	 * @param v1
	 * @param v2
	 * @return
	 */
	public static boolean isLongEqual(Long v1, Long v2) {
		if ((v1 == null && v2 != null) || (v1 != null && v2 == null)) {
			return false;
		} else if (v1 == null && v2 == null) {
			return true;
		} else {
			return v1.equals(v2);
		}
	}

	/**
	 * @param s1
	 * @param s2
	 * @return
	 */
	public static boolean equals(String s1, String s2) {
		if (xx.isEmpty(s1) || xx.isEmpty(s2)) {
			return false;
		}
		return s1.equals(s2);
	}

	/**
	 * 比较数字是否相等。
	 *
	 * @param int1
	 * @param int2
	 * @return
	 */
	public static boolean equals(Integer int1, Integer int2) {
		if (int1 == null || int2 == null) {
			return false;
		}
		return int1.intValue() == int2.intValue();
	}

	/**
	 * 比较数字是否相等。
	 *
	 * @param int1
	 * @param int2
	 * @return
	 */
	public static boolean equals(Integer int1, int int2) {
		if (int1 == null) {
			return false;
		}
		return int1.intValue() == int2;
	}

	public static Ret setStatusAndMsg(boolean flag, String msg) {
		Ret ret = new Ret();
		ret.set("flag", flag);
		ret.set("msg", msg);
		return ret;
	}

	/**
	 * 获取配置项的值
	 * @param key
	 * @return
	 */
	public static String getConfigValue(String key) {
		MainConfig config = new MainConfig();
		Prop prop = config.getUtilProp();
		return prop.get(key).toString();
	}
}